package org.eclipse.gmf.internal.bridge.wizards;

import java.util.HashMap;
import java.io.*;
import java.io.File;
import org.eclipse.gmf.internal.bridge.wizards.pages.TransformationsPage;
import java.util.Map;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.ContentHandler;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;
import org.eclipse.gmf.internal.bridge.resolver.StructureResolver;
import org.eclipse.gmf.internal.bridge.ui.Plugin;
import org.eclipse.gmf.internal.bridge.wizards.pages.simple.DefinitionPage;
import org.eclipse.gmf.internal.bridge.wizards.pages.simple.DomainModelSelectionPage;
import org.eclipse.gmf.internal.bridge.wizards.pages.simple.DomainModelSourceImpl;
import org.eclipse.gmf.internal.bridge.wizards.pages.simple.StructureBuilder;
import org.eclipse.gmf.internal.bridge.wizards.pages.simple.ToolDefBuilder;
import org.eclipse.gmf.internal.common.URIUtil;
import org.eclipse.gmf.internal.common.ui.ModelSelectionPage;
import org.eclipse.gmf.internal.common.ui.ResourceLocationProvider;
import org.eclipse.gmf.tooldef.ToolRegistry;
import org.eclipse.gmf.tooldef.presentation.GMFToolModelWizard;
import org.eclipse.gmf.tooldef.presentation.GMFToolModelWizard.GMFToolModelWizardNewFileCreationPage;
import org.eclipse.gmf.tooldef.provider.GMFToolEditPlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.ISetSelectionTarget;

public class GMFTransformationsSimpleModelWizard extends GMFTransformationsModelWizard {

	protected ModelSelectionPage transformationModelSelectionPage;

	protected DefinitionPage transformationDefinitionPage;
	
	protected TransformationsPage transformationsPage;

	protected WizardOperationMode mode = new WizardOperationMode("txt", WizardOperationMode.CREATE); //$NON-NLS-1$

	public void setMode(String mode) {
		this.mode.setMode(mode);
	}

	/**
	 * Returns true if wizard operates in reconcile mode.
	 * Resource must be available if returns true.
	 */
	protected boolean isInReconcileMode() {
		return transformationModelSelectionPage != null && transformationModelSelectionPage.getResource() != null;
	}
	
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.workbench = workbench;
		this.selection = selection;
		setWindowTitle(GMFToolEditPlugin.INSTANCE.getString("_UI_Wizard_label"));
		setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE.getImageDescriptor(GMFToolEditPlugin.INSTANCE.getImage("full/wizban/NewGMFTool")));
	}

	public boolean performFinish() {
		if (isInReconcileMode()) {
			reconcileModel();
			try {
				WizardUtil.saveModel(getContainer(), transformationModelSelectionPage.getResource());
			} catch (Exception exception) {
				Plugin.log(exception);
				return false;
			}
			IFile modelFile = getModelFile();
			if (modelFile != null) {
				WizardUtil.openEditor(modelFile);
			}
			return true;
		} else {
			return super.performFinish();
		}
	}

	protected EObject createInitialModel() {
		ToolDefBuilder builder = new ToolDefBuilder(null);
		return builder.process(transformationDefinitionPage.getModel());
	}

	protected void reconcileModel() {
		ToolRegistry existingToolRegistry = null;
		for (EObject element : transformationModelSelectionPage.getResource().getContents()) {
			if (element instanceof ToolRegistry) {
				existingToolRegistry = (ToolRegistry) element;
				break;
			}
		}
		ToolDefBuilder builder = new ToolDefBuilder(existingToolRegistry);
		ToolRegistry toolRegistry = builder.process(transformationDefinitionPage.getModel());
		if (toolRegistry != null && existingToolRegistry != toolRegistry) {
			transformationModelSelectionPage.getResource().getContents().add(toolRegistry);
		}
	}

	public void addPages() {
		ResourceLocationProvider rloc = new ResourceLocationProvider(selection);
		ResourceSet resourceSet = new ResourceSetImpl();
		if (mode.detectReconcile(rloc)) {
			transformationModelSelectionPage = new ModelSelectionPage("transformationModelSelectionPage", rloc, resourceSet, "txt"); //$NON-NLS-1$ //$NON-NLS-2$
			transformationModelSelectionPage.setPageComplete(false);
			transformationModelSelectionPage.setModelRequired(true);
			transformationModelSelectionPage.setTitle(Messages.SimpleModelWizardToolModelSelectionPageTitle);
			transformationModelSelectionPage.setDescription(Messages.SimpleModelWizardToolModelSelectionPageDesc);
			addPage(transformationModelSelectionPage);
		} else {
			super.addPages();
			if (selection != null && !selection.isEmpty()) {
				Object selected = selection.getFirstElement();
				if (selected instanceof IFile) {
					newFileCreationPage.setFileName(WizardUtil.getDefaultFileName((IFile) selected, "txt")); //$NON-NLS-1$
				}
			}
		}

		DomainModelSelectionPage domainModelSelectionPage = new DomainModelSelectionPage("DomainModelSelectionPage", rloc, resourceSet); //$NON-NLS-1$
		domainModelSelectionPage.setTitle("New Model");
		domainModelSelectionPage.setDescription("Select file with the new model.");
		addPage(domainModelSelectionPage);

		transformationDefinitionPage = new DefinitionPage("transformationDefinitionPage", new StructureBuilder(new StructureResolver(), false), domainModelSelectionPage) { //$NON-NLS-1$

			protected DomainModelSourceImpl createDomainModelSource(EPackage contents, EClass diagramElement) {
				if (isInReconcileMode()) {
					return new DomainModelSourceImpl(contents, diagramElement) {

						public boolean isDisabled(EObject domainElement) {
							return ToolDefBuilder.getCreationTool(transformationModelSelectionPage.getResource().getAllContents(), domainElement) != null;
						}
					};
				}
				return super.createDomainModelSource(contents, diagramElement);
			}
		};
		transformationDefinitionPage.setTitle("Transformation Definition");
		transformationDefinitionPage.setDescription("Specify basic tooling definition of the new model.");
		//addPage(transformationDefinitionPage);
		
		transformationsPage = new TransformationsPage("Transformations Page", rloc, resourceSet, "txt");
		transformationsPage.setTitle("Transformations");
		transformationsPage.setDescription("Select files with the transforamtions.");
		transformationsPage.setPageComplete(false);
		transformationsPage.setModelRequired(true);
		addPage(transformationsPage);
	}

	public IFile getModelFile() {
		//if (isInReconcileMode()) {
			//return URIUtil.getFile(transformationModelSelectionPage.getResource().getURI());
		//}
		String str = transformationsPage.getStr();
		str = str.substring(4);
		ResourceSet resourceSet = new ResourceSetImpl();
		File f1 = new File("D:/in.txt");
		
		IFile file;
		
		//File file = new File(URIUtil.getFile(transformationModelSelectionPage.getResource().getURI()).getName());
		if (isInReconcileMode()) {
			Resource resource = resourceSet.createResource(transformationModelSelectionPage.getResource().getURI(), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
			file = URIUtil.getFile(resource.getURI()); 
		}
		else	{
			file = super.getModelFile();
		}
		try{
		InputStream inputStream = new ByteArrayInputStream(str.getBytes("UTF8"));
		FileWriter wr = new FileWriter(f1);
		wr.write(str);
		wr.close();
		file.create(inputStream, true, null);
		} catch(Exception e) {
			System.out.println(e.getLocalizedMessage());
		}
		return file;
		
		//return URIUtil.getFile(transformationsPage.getResource().getURI());
		
		//return super.getModelFile();
	}
}